/*
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Authors:
 *  	Albert Marieges Garcia
 *  	Álex Pardo Fernández
 *  	Enric Mayas Márquez
 *  	Juan Carlos Calvo Tejedor
 *  	Marc Gironés Dezsényi
 *  
 *  Contact:
 *  	bcn.tours.android@gmail.com
 *  Webpage:
 *  	bcntours.co.cc
 *
 */


package com.BCNTours.Vista;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Spinner;

import com.BCNTours.R;
import com.BCNTours.Model.ApplicationData;

/**
 * Shows the preference menu with a list of options such as language, unit to represent the distance, to show application related info...
 *
 */
public class Preferences extends Activity{
	/*Attributions*/
	@SuppressWarnings("unused")
	private Spinner spLang;
    private ApplicationData applicationData;
    public static final String PREF_LANG = "PREF_LANG"; 
    public static final String PREF_UNITS = "PREF_UNITS"; 
    private int lang;
    private int prevLang;
    private int units;
    private SharedPreferences prefs;

	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.preferences);
		
        //Get all extras previously added with putExtra()
        Bundle extras = getIntent().getExtras();
        applicationData = (ApplicationData) extras.getSerializable("com.ShowMe.Model.PoiList");
        
        //Load preferences
		prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); 
        updatePreferences();
		
        //Animation of the screen
		@SuppressWarnings("unused")
		LayoutInflater mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
	}
	
	
    /**
     * BtnActionListener of the preferences
     */
    public void btnPreferencesPerformed(View view){
    	switch(view.getId()){
    	
    	//Language
    	case R.id.btnLanguage:
    		languageDialog();
    		break;
    		
    	// Units set
    	case R.id.btnUnits:
    		unitsDialog();
    		break;
    		
		//Filter button
		case R.id.btnFilter:
			filterDialog();
			break;
		
		//About
		case R.id.btnAbout:
			Dialog aboutDialog = new Dialog(Preferences.this);
			aboutDialog.setTitle("About");
			aboutDialog.setContentView(R.layout.about_dialog);
			aboutDialog.show();
			break;
    	}
    }

    /**
     * Create and manage the language dialog
     */
    private void languageDialog(){
    	final CharSequence[] items = {new StringBuffer(getString(R.string.msgSpanishLanguage)), 
										new StringBuffer(getString(R.string.msgCatalaLanguage)),
										new StringBuffer(getString(R.string.msgEnglishLanguage))};
		
		//Create a single choice dialog window
	    AlertDialog.Builder builderLanguage = new AlertDialog.Builder(this);
	    builderLanguage.setTitle(R.string.msgLanguageDialog);
	    builderLanguage.setSingleChoiceItems(items, lang-1, new DialogInterface.OnClickListener() {
	    	
	    	//Save the length unit in the database and close the dialog
	    	public void onClick(DialogInterface dialog, int item) {
	    		lang = item+1;
	    		savePreferences();
	            dialog.cancel();
	        }
	    });
	    
	    //Create and show the restore dialog
	    builderLanguage.create();
	    builderLanguage.show();
    }
    
    /**
     * Create and manage the length unit dialog
     */
    private void unitsDialog(){
    	final CharSequence[] items = {new StringBuffer(getString(R.string.msgUnitKm)), 
										new StringBuffer(getString(R.string.msgUnitMile)), 
										new StringBuffer(getString(R.string.msgUnitYard))};
		
		//Create a single choice dialog window
	    AlertDialog.Builder builderUnits = new AlertDialog.Builder(this);
	    builderUnits.setTitle(R.string.msgUnitDialog);
	    builderUnits.setSingleChoiceItems(items, units, new DialogInterface.OnClickListener() {
	    	
	    	//Save the length unit in the database and close the dialog
	    	public void onClick(DialogInterface dialog, int item) {
	    		units = item;
	    		savePreferences();
	            dialog.cancel();
	        }
	    });
	    
	    //Create and show the restore dialog
		builderUnits.create();
		builderUnits.show();
    }
    
    
    /**
     * Create and manage the filter setting dialog
     */
    private void filterDialog(){
		final CharSequence[] filterList = {new StringBuffer(getString(R.string.msgMonuments)), 
											new StringBuffer(getString(R.string.msgAttracions)), 
											new StringBuffer(getString(R.string.msgMuseums)), 
											new StringBuffer(getString(R.string.msgInfoPoint))};
		
		final boolean [] filterPreferences = applicationData.getFilterPreferences();
		
		//Create a multichoice dialog window
		AlertDialog.Builder builderFilter = new AlertDialog.Builder(this);
		builderFilter.setTitle(R.string.msgFilterDialog);
		builderFilter.setMultiChoiceItems(filterList, filterPreferences, new DialogInterface.OnMultiChoiceClickListener() {
			public void onClick(DialogInterface dialog, int which, boolean isChecked) {
				filterPreferences[which] = isChecked;
			}
		});
		
		//Save the settings in the database
		builderFilter.setPositiveButton(R.string.msgOk, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	applicationData.setFilterPreferences(filterPreferences);
            }
        });
        
		//Close the dialog
        builderFilter.setNegativeButton(R.string.msgCancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	dialog.cancel();
            }
        });
        
        //Create and show the restore dialog
		builderFilter.create();
		builderFilter.show();
    }
    
	/*
	 * Loads the previously saved preferences or the default ones
	 */
	private void updatePreferences() { 
		lang= prefs.getInt(PREF_LANG, 3); 
		prevLang = lang;
		units = prefs.getInt(PREF_UNITS, 0);
	}
	
	/*
	 * Saves the selected preferences
	 */
	private void savePreferences() { 
		Editor editor = prefs.edit(); 
		editor.putInt(PREF_LANG, lang); 
		editor.putInt(PREF_UNITS, units); 
		editor.commit();

		if(lang != prevLang){
			AlertDialog.Builder builderRestore = new AlertDialog.Builder(this);
			prevLang = lang;
			builderRestore.setMessage(R.string.msgRestart)
			       .setCancelable(false)
			       .setPositiveButton(R.string.msgYes, new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   Intent intent = new Intent();
			        	   intent.putExtra("com.ShowMe.Model.PoiList", applicationData);
			               setResult(0,intent);
			               finish();
			        	   
			        	   	
			   				
			           }
			       })
			       .setNegativeButton(R.string.msgRestartLater, new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			           }
			       });
			
			//Create and show the restore dialog
			builderRestore.create();
			builderRestore.show();
		}
	}
	
	@Override
	public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra("com.ShowMe.Model.PoiList", applicationData);
        setResult(1,intent);
        finish();
	}
}
